from django.shortcuts import render
import time
import json
import re
import logging
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.utils import timezone
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q
from django.shortcuts import get_object_or_404

from .models import AdminUser, Department, Role, Resource, RoleResource, Workflow, WorkflowPermission, Position, WorkflowApprovalNode, Task, AuditRecord
from .serializers import AdminUserSerializer, AdminLoginSerializer, DepartmentSerializer, RoleSerializer, ResourceSerializer, WorkflowSerializer, WorkflowPermissionSerializer, PositionSerializer, WorkflowApprovalNodeSerializer, TaskSerializer, AuditRecordSerializer
from util.myrediss import r
from util.myjwt import myjwt
from util.sms_utils import sms
from util.imgage_code import random_code, make_verify_image

logger = logging.getLogger(__name__)

@require_http_methods(["GET"])
def get_admin_image_code(request):
    """
    生成并返回管理后台图片验证码
    
    参数:
        request: HTTP请求对象，需要包含uuid参数
        
    流程:
        1. 获取前端传递的uuid参数
        2. 生成4位随机验证码
        3. 将验证码存入Redis，过期时间300秒(5分钟)
        4. 根据验证码生成图片
        5. 返回图片数据
        
    返回:
        成功: 图片数据(image/jpeg)
        失败: JSON错误信息
    """
    try:
        uuid = request.GET.get('uuid')
        if not uuid:
            return JsonResponse({'code': 400, 'message': '缺少uuid参数'})
        # 生成新验证码
        code = random_code(4)
        # 存入 redis，key 用 uuid，添加admin_前缀区分
        r.set_value_time(f'admin_{uuid}', code, 300)
        # 生成图片
        image_data = make_verify_image(code)
        # 使用HttpResponse而不是JsonResponse返回二进制图片数据
        response = HttpResponse(image_data, content_type='image/jpeg')
        response['Access-Control-Allow-Origin'] = '*'
        return response
    except Exception as e:
        logger.error(f"生成管理员图片验证码失败: {str(e)}")
        return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

@csrf_exempt
@require_http_methods(["POST"])
def send_admin_verification_code(request):
    """
    发送管理员短信验证码
    
    参数:
        request: HTTP请求对象，请求体应包含以下JSON数据:
            - mobile: 手机号码
            - image_code: 图片验证码
            - uuid: 图片验证码对应的uuid
            
    流程:
        1. 验证手机号格式
        2. 验证图片验证码是否正确
        3. 检查是否在1分钟内重复发送
        4. 检查手机号是否属于管理员
        5. 生成短信验证码
        6. 调用短信服务发送验证码
        7. 将验证码存入Redis，过期时间300秒(5分钟)
        8. 删除已使用的图片验证码
        
    返回:
        成功: {'code': 200, 'message': '验证码发送成功'}
        失败: {'code': 4xx/5xx, 'message': 错误信息}
    """
    try:
        # 记录请求数据
        logger.info(f"接收到发送验证码请求，请求体: {request.body}")
        
        data = json.loads(request.body)
        mobile = data.get('mobile')
        image_code = data.get('image_code')
        uuid = data.get('uuid')
        
        logger.info(f"解析请求数据: mobile={mobile}, image_code={image_code}, uuid={uuid}")
        
        # 确保mobile是字符串类型
        if mobile is not None and not isinstance(mobile, str):
            mobile = str(mobile)
            logger.info(f"将mobile转换为字符串: {mobile}")
        
        if not mobile or not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'message': '手机号格式不正确'})
            
        if not uuid:
            return JsonResponse({'code': 400, 'message': '缺少uuid参数'})
            
        # 验证图片验证码（不区分大小写）
        stored_code = r.get_value(f'admin_{uuid}')
        logger.info(f"从Redis获取的验证码: {stored_code}")
        
        # 确保image_code是字符串类型
        if not image_code or not isinstance(image_code, str):
            logger.warning(f"图片验证码格式不正确: {type(image_code)}")
            return JsonResponse({'code': 400, 'message': '图片验证码格式不正确'})
            
        # 确保stored_code存在且可以解码
        if not stored_code:
            logger.warning(f"Redis中不存在验证码: admin_{uuid}")
            return JsonResponse({'code': 400, 'message': '图片验证码已过期或不存在'})
            
        try:
            decoded_stored_code = stored_code.decode().lower()
            logger.info(f"解码后的存储验证码: {decoded_stored_code}, 用户输入验证码: {image_code.lower()}")
            if decoded_stored_code != image_code.lower():
                return JsonResponse({'code': 400, 'message': '图片验证码错误'})
        except Exception as e:
            logger.error(f"解码存储的验证码失败: {str(e)}")
            return JsonResponse({'code': 400, 'message': '验证码验证失败'})
            
        # 检查是否在1分钟内重复发送
        if r.get_value(f'admin_sms_send_{mobile}'):
            return JsonResponse({'code': 400, 'message': '请1分钟后再试'})
            
        # 检查手机号是否属于管理员
        admin_exists = AdminUser.objects.filter(phone=mobile, is_deleted=False).exists()
        logger.info(f"手机号 {mobile} 是否为管理员: {admin_exists}")
        if not admin_exists:
            return JsonResponse({'code': 404, 'message': '该手机号未注册为管理员'})
            
        # 生成短信验证码
        sms_code = sms.generate_code()
        logger.info(f"生成的短信验证码: {sms_code}")
        
        # 发送短信验证码
        logger.info(f"开始发送短信验证码: mobile={mobile}, code={sms_code}")
        try:
            success, message = sms.send_sms(mobile, sms_code)
            logger.info(f"短信发送结果: success={success}, message={message}")
        except Exception as e:
            logger.error(f"发送短信时出现异常: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return JsonResponse({'code': 500, 'message': f'短信发送异常: {str(e)}'})
        
        if success:
            # 存储验证码到Redis，添加admin_前缀区分
            r.set_value_time(f'admin_sms_code_{mobile}', sms_code, 300)  # 5分钟过期
            r.set_value_time(f'admin_sms_send_{mobile}', '1', 60)  # 1分钟内不能重复发送
            r.client.delete(f'admin_{uuid}')  # 删除已使用的图片验证码
            return JsonResponse({'code': 200, 'message': '验证码发送成功'})
        else:
            return JsonResponse({'code': 500, 'message': f'验证码发送失败：{message}'})
            
    except Exception as e:
        logger.error(f"发送管理员短信验证码失败: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

@csrf_exempt
@require_http_methods(["POST"])
def admin_login(request):
    """
    管理员登录接口
    
    参数:
        request: HTTP请求对象，请求体应包含以下JSON数据:
            - phone: 手机号码
            - password: 密码（密码登录时必填）
            - sms_code: 短信验证码（短信登录时必填）
            - login_type: 登录类型，'password'或'sms'
            
    流程:
        1. 验证请求数据
        2. 根据登录类型进行不同的验证:
           - 密码登录: 验证手机号和密码
           - 短信登录: 验证手机号和短信验证码
        3. 查询管理员用户
        4. 生成JWT token，有效期24小时
        5. 更新最后登录时间
        6. 获取管理员的角色和权限
        
    返回:
        成功: {
            'code': 200, 
            'message': '登录成功',
            'data': {
                'userid': 用户ID,
                'token': JWT令牌,
                'name': 管理员姓名,
                'phone': 手机号,
                'role': 角色信息,
                'permissions': 权限列表
            }
        }
        失败: {'code': 4xx/5xx, 'message': 错误信息}
    """
    try:
        data = json.loads(request.body)
        serializer = AdminLoginSerializer(data=data)
        
        if not serializer.is_valid():
            return JsonResponse({'code': 400, 'message': serializer.errors})
            
        validated_data = serializer.validated_data
        phone = validated_data.get('phone')
        login_type = validated_data.get('login_type')
        
        # 查询管理员用户
        try:
            admin_user = AdminUser.objects.get(phone=phone, is_deleted=False)
        except AdminUser.DoesNotExist:
            return JsonResponse({'code': 404, 'message': '该手机号未注册为管理员'})
            
        # 根据登录类型进行验证
        if login_type == 'password':
            password = validated_data.get('password')
            
            # 这里应该使用加密后的密码比较，示例中为了简单直接比较明文
            # 实际应用中应该使用如下方式验证密码:
            # from django.contrib.auth.hashers import check_password
            # if not check_password(password, admin_user.password):
            if password != admin_user.password:
                return JsonResponse({'code': 401, 'message': '密码错误'})
                
        elif login_type == 'sms':
            sms_code = validated_data.get('sms_code')
            
            # 验证短信验证码
            stored_sms_code = r.get_value(f'admin_sms_code_{phone}')
            if not stored_sms_code or stored_sms_code.decode() != sms_code:
                return JsonResponse({'code': 401, 'message': '验证码错误或已过期'})
                
            # 删除已使用的短信验证码
            r.client.delete(f'admin_sms_code_{phone}')
        
        # 更新最后登录时间
        admin_user.last_login = timezone.now()
        admin_user.save(update_fields=['last_login'])
        
        # 生成token，添加过期时间（24小时）
        token = myjwt.encode({
            'userid': admin_user.id,
            'name': admin_user.name,
            'is_admin': True,  # 标记为管理员
            'exp': int(time.time()) + 24 * 3600  # 24小时过期
        })
        
        # 存储token到redis，用于验证用户是否退出登录
        r.set_value_time(f'admin_token_{admin_user.id}', token, 24 * 3600)  # 24小时过期
        
        # 获取管理员角色
        role = admin_user.role
        role_data = RoleSerializer(role).data
        
        # 获取管理员权限
        permissions = []
        role_resources = RoleResource.objects.filter(role=role).select_related('resource')
        for role_resource in role_resources:
            resource = role_resource.resource
            permissions.append({
                'id': resource.id,
                'name': resource.name,
                'url': resource.url,
                'pid': resource.pid_id
            })
        
        # 构建返回数据
        response_data = {
            'userid': admin_user.id,
            'token': token,
            'name': admin_user.name,
            'phone': admin_user.phone,
            'role': role_data,
            'department': {
                'id': admin_user.department.id,
                'name': admin_user.department.name
            },
            'permissions': permissions
        }
        
        return JsonResponse({
            'code': 200,
            'message': '登录成功',
            'data': response_data
        })
        
    except Exception as e:
        logger.error(f"管理员登录失败: {str(e)}")
        import traceback
        logger.error(traceback.format_exc())
        return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

@csrf_exempt
@require_http_methods(["POST"])
def admin_logout(request):
    """
    管理员退出登录
    
    参数:
        request: HTTP请求对象
        
    流程:
        1. 从request中获取管理员信息（中间件添加的）
        2. 从redis中删除token
        
    返回:
        成功: {'code': 200, 'message': '退出成功'}
        失败: {'code': 4xx/5xx, 'message': 错误信息}
    """
    try:
        # 从request中获取用户信息（中间件添加的）
        admin_info = getattr(request, 'admin_info', None)
        if not admin_info:
            return JsonResponse({'code': 401, 'message': '未登录'})
            
        # 从redis中删除token
        user_id = admin_info.get('userid')
        r.client.delete(f'admin_token_{user_id}')
        
        return JsonResponse({
            'code': 200,
            'message': '退出成功'
        })
    except Exception as e:
        logger.error(f"管理员退出登录失败: {str(e)}")
        return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

@method_decorator(csrf_exempt, name='dispatch')
class AdminInfoView(APIView):
    """
    管理员信息API视图类
    """
    
    def get(self, request):
        """
        获取当前登录管理员信息
        
        参数:
            request: HTTP请求对象
            
        流程:
            1. 从request中获取管理员信息（中间件添加的）
            2. 查询管理员详细信息
            3. 获取管理员角色和权限
            
        返回:
            成功: {'code': 200, 'data': 管理员信息}
            失败: {'code': 4xx, 'message': 错误信息}
        """
        try:
            # 从request中获取用户信息（中间件添加的）
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 查询管理员详细信息
            try:
                admin_user = AdminUser.objects.get(id=admin_info['userid'], is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '管理员不存在或已被删除'})
                
            # 序列化管理员信息
            serializer = AdminUserSerializer(admin_user)
            
            # 获取管理员角色
            role = admin_user.role
            role_data = RoleSerializer(role).data
            
            # 获取管理员权限
            permissions = []
            role_resources = RoleResource.objects.filter(role=role).select_related('resource')
            for role_resource in role_resources:
                resource = role_resource.resource
                permissions.append({
                    'id': resource.id,
                    'name': resource.name,
                    'url': resource.url,
                    'pid': resource.pid_id
                })
            
            # 构建返回数据
            response_data = serializer.data
            response_data['role_info'] = role_data
            response_data['permissions'] = permissions
            response_data['department_info'] = {
                'id': admin_user.department.id,
                'name': admin_user.department.name
            }
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': response_data
            })
            
        except Exception as e:
            logger.error(f"获取管理员信息失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})
            
    def put(self, request):
        """
        更新当前登录管理员信息
        
        参数:
            request: HTTP请求对象，请求体应包含要更新的字段
             
        流程:
            1. 从request中获取管理员信息（中间件添加的）
            2. 查询管理员详细信息
            3. 更新管理员信息
            
        返回:
            成功: {'code': 200, 'message': '更新成功', 'data': 更新后的管理员信息}
            失败: {'code': 4xx/5xx, 'message': 错误信息}
        """
        try:
            # 从request中获取用户信息（中间件添加的）
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 查询管理员详细信息
            try:
                admin_user = AdminUser.objects.get(id=admin_info['userid'], is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '管理员不存在或已被删除'})
                
            # 获取要更新的字段
            data = request.data
            
            # 只允许更新部分字段
            allowed_fields = ['name']
            update_data = {}
            
            for field in allowed_fields:
                if field in data:
                    update_data[field] = data[field]
                    
            # 如果要更新密码，需要验证旧密码
            if 'password' in data and 'old_password' in data:
                old_password = data['old_password']
                new_password = data['password']
                
                # 验证旧密码
                # 实际应用中应该使用如下方式验证密码:
                # from django.contrib.auth.hashers import check_password, make_password
                # if not check_password(old_password, admin_user.password):
                if old_password != admin_user.password:
                    return Response({'code': 400, 'message': '旧密码错误'})
                    
                # 更新密码
                # 实际应用中应该使用如下方式加密密码:
                # update_data['password'] = make_password(new_password)
                update_data['password'] = new_password
                
            # 如果没有要更新的字段
            if not update_data:
                return Response({'code': 400, 'message': '没有要更新的字段'})
                
            # 更新管理员信息
            for field, value in update_data.items():
                setattr(admin_user, field, value)
                
            admin_user.save()
            
            # 序列化更新后的管理员信息
            serializer = AdminUserSerializer(admin_user)
            
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })
            
        except Exception as e:
            logger.error(f"更新管理员信息失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})

@method_decorator(csrf_exempt, name='dispatch')
class DoctorPermissionView(APIView):
    """
    医生权限管理API视图类
    
    提供医院管理人员对其他医生用户权限的管理功能
    只有院长级别的用户可以管理其他医生的权限
    """
    
    def get(self, request, doctor_id=None):
        """
        获取医生列表或特定医生的权限信息
        
        参数:
            doctor_id: 路径参数，医生ID，不传则返回所有医生列表
            
        返回:
            {'code': 200, 'data': 医生列表或医生权限信息}
        """
        try:
            # 检查权限
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 验证用户是否有管理权限
            admin_id = admin_info.get('userid')
            try:
                admin_user = AdminUser.objects.get(id=admin_id, is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '管理员不存在或已被删除'})
                
            # 检查是否有系统管理权限
            role_resources = RoleResource.objects.filter(role=admin_user.role).select_related('resource')
            has_permission = False
            for role_resource in role_resources:
                if '系统管理' in role_resource.resource.name:
                    has_permission = True
                    break
                    
            if not has_permission:
                return Response({'code': 403, 'message': '没有系统管理权限'})
                
            # 如果传入了doctor_id，获取特定医生的信息
            if doctor_id:
                try:
                    doctor = AdminUser.objects.get(id=doctor_id, is_deleted=False)
                except AdminUser.DoesNotExist:
                    return Response({'code': 404, 'message': '医生不存在或已被删除'})
                    
                # 获取医生的角色和权限信息
                doctor_serializer = AdminUserSerializer(doctor)
                role = doctor.role
                role_serializer = RoleSerializer(role)
                
                # 获取医生的权限资源
                resources = []
                role_resources = RoleResource.objects.filter(role=role).select_related('resource')
                for role_resource in role_resources:
                    resource = role_resource.resource
                    resources.append({
                        'id': resource.id,
                        'name': resource.name,
                        'url': resource.url,
                        'pid': resource.pid_id
                    })
                
                return Response({
                    'code': 200,
                    'message': '获取成功',
                    'data': {
                        'doctor': doctor_serializer.data,
                        'role': role_serializer.data,
                        'resources': resources
                    }
                })
            else:
                # 获取所有医生列表
                doctors = AdminUser.objects.filter(is_deleted=False)
                
                # 构建包含权限资源的响应数据
                doctor_list = []
                for doctor in doctors:
                    doctor_data = AdminUserSerializer(doctor).data
                    
                    # 获取医生的权限资源
                    resources = []
                    role_resources = RoleResource.objects.filter(role=doctor.role).select_related('resource')
                    for role_resource in role_resources:
                        resource = role_resource.resource
                        resources.append({
                            'id': resource.id,
                            'name': resource.name,
                            'url': resource.url,
                            'pid': resource.pid_id
                        })
                    
                    # 添加资源到医生数据中
                    doctor_data['resources'] = resources
                    doctor_list.append(doctor_data)
                
                return Response({
                    'code': 200,
                    'message': '获取成功',
                    'data': doctor_list
                })
                
        except Exception as e:
            logger.error(f"获取医生权限信息失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})
    
    def put(self, request, doctor_id):
        """
        更新医生权限
        
        参数:
            doctor_id: 路径参数，医生ID
            请求体应包含:
            - role_id: 角色ID，用于更改医生的角色
            或
            - resources: 资源ID列表，用于直接设置医生角色的权限
            
        返回:
            {'code': 200, 'message': '更新成功', 'data': 更新后的医生权限信息}
        """
        try:
            # 检查权限
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 验证用户是否有管理权限
            admin_id = admin_info.get('userid')
            try:
                admin_user = AdminUser.objects.get(id=admin_id, is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '管理员不存在或已被删除'})
                
            # 检查是否有系统管理权限
            role_resources = RoleResource.objects.filter(role=admin_user.role).select_related('resource')
            has_permission = False
            for role_resource in role_resources:
                if '系统管理' in role_resource.resource.name:
                    has_permission = True
                    break
                    
            if not has_permission:
                return Response({'code': 403, 'message': '没有系统管理权限'})
                
            # 获取要更新的医生
            try:
                doctor = AdminUser.objects.get(id=doctor_id, is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '医生不存在或已被删除'})
                
            # 获取请求数据
            data = request.data
            role_id = data.get('role_id')
            resources = data.get('resources')
            
            # 更新医生角色
            if role_id:
                try:
                    new_role = Role.objects.get(id=role_id)
                    doctor.role = new_role
                    doctor.save(update_fields=['role', 'updated_at'])
                    
                    logger.info(f"医生 {doctor.name}(ID: {doctor.id}) 的角色已更新为 {new_role.name}(ID: {new_role.id})")
                    
                except Role.DoesNotExist:
                    return Response({'code': 404, 'message': '指定的角色不存在'})
            
            # 更新医生角色的权限
            if resources and isinstance(resources, list):
                # 获取医生当前的角色
                role = doctor.role
                
                # 先清除该角色的所有权限
                RoleResource.objects.filter(role=role).delete()
                
                # 添加新的权限
                added_resources = []
                for resource_id in resources:
                    try:
                        resource = Resource.objects.get(id=resource_id)
                        RoleResource.objects.create(role=role, resource=resource)
                        added_resources.append(resource.name)
                    except Resource.DoesNotExist:
                        logger.warning(f"资源 ID: {resource_id} 不存在")
                        continue
                
                logger.info(f"医生 {doctor.name}(ID: {doctor.id}) 的角色 {role.name}(ID: {role.id}) 权限已更新，新增资源: {', '.join(added_resources)}")
            
            # 获取更新后的医生信息和权限
            doctor_serializer = AdminUserSerializer(doctor)
            role = doctor.role
            role_serializer = RoleSerializer(role)
            
            # 获取医生的权限资源
            updated_resources = []
            role_resources = RoleResource.objects.filter(role=role).select_related('resource')
            for role_resource in role_resources:
                resource = role_resource.resource
                updated_resources.append({
                    'id': resource.id,
                    'name': resource.name,
                    'url': resource.url,
                    'pid': resource.pid_id
                })
            
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'doctor': doctor_serializer.data,
                    'role': role_serializer.data,
                    'resources': updated_resources
                }
            })
            
        except Exception as e:
            logger.error(f"更新医生权限失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})
            
    def post(self, request):
        """
        添加医生用户
        
        参数:
            请求体应包含:
            - name: 医生姓名
            - phone: 手机号
            - password: 密码
            - role_id: 角色ID
            - department_id: 部门ID
            
        返回:
            {'code': 201, 'message': '添加成功', 'data': 新增医生信息}
        """
        try:
            # 检查权限
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 验证用户是否有管理权限
            admin_id = admin_info.get('userid')
            try:
                admin_user = AdminUser.objects.get(id=admin_id, is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '管理员不存在或已被删除'})
                
            # 检查是否有系统管理权限
            role_resources = RoleResource.objects.filter(role=admin_user.role).select_related('resource')
            has_permission = False
            for role_resource in role_resources:
                if '系统管理' in role_resource.resource.name:
                    has_permission = True
                    break
                    
            if not has_permission:
                return Response({'code': 403, 'message': '没有系统管理权限'})
                
            # 获取请求数据
            data = request.data
            name = data.get('name')
            phone = data.get('phone')
            password = data.get('password')
            role_id = data.get('role_id')
            department_id = data.get('department_id')
            
            # 验证必填字段
            if not all([name, phone, password, role_id, department_id]):
                return Response({'code': 400, 'message': '缺少必要参数'})
                
            # 验证手机号格式
            if not re.match(r'^1[3-9]\d{9}$', phone):
                return Response({'code': 400, 'message': '手机号格式不正确'})
                
            # 检查手机号是否已存在
            if AdminUser.objects.filter(phone=phone, is_deleted=False).exists():
                return Response({'code': 400, 'message': '该手机号已被注册'})
                
            # 获取角色和部门
            try:
                role = Role.objects.get(id=role_id)
            except Role.DoesNotExist:
                return Response({'code': 404, 'message': '指定的角色不存在'})
                
            try:
                department = Department.objects.get(id=department_id)
            except Department.DoesNotExist:
                return Response({'code': 404, 'message': '指定的部门不存在'})
                
            # 创建医生用户
            # 实际应用中应该使用如下方式加密密码:
            # from django.contrib.auth.hashers import make_password
            # password = make_password(password)
            
            new_doctor = AdminUser.objects.create(
                name=name,
                phone=phone,
                password=password,
                role=role,
                department=department
            )
            
            logger.info(f"新增医生用户 {name}(ID: {new_doctor.id})，角色: {role.name}，部门: {department.name}")
            
            # 返回新增的医生信息
            serializer = AdminUserSerializer(new_doctor)
            
            # 获取新医生的权限资源
            resources = []
            role_resources = RoleResource.objects.filter(role=new_doctor.role).select_related('resource')
            for role_resource in role_resources:
                resource = role_resource.resource
                resources.append({
                    'id': resource.id,
                    'name': resource.name,
                    'url': resource.url,
                    'pid': resource.pid_id
                })
            
            return Response({
                'code': 201,
                'message': '添加成功',
                'data': {
                    'doctor': serializer.data,
                    'resources': resources
                }
            })
            
        except Exception as e:
            logger.error(f"添加医生用户失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})
            
    def delete(self, request, doctor_id):
        """
        删除医生用户（软删除）
        
        参数:
            doctor_id: 路径参数，医生ID
            
        返回:
            {'code': 200, 'message': '删除成功'}
        """
        try:
            # 检查权限
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 验证用户是否有管理权限
            admin_id = admin_info.get('userid')
            try:
                admin_user = AdminUser.objects.get(id=admin_id, is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '管理员不存在或已被删除'})
                
            # 检查是否有系统管理权限
            role_resources = RoleResource.objects.filter(role=admin_user.role).select_related('resource')
            has_permission = False
            for role_resource in role_resources:
                if '系统管理' in role_resource.resource.name:
                    has_permission = True
                    break
                    
            if not has_permission:
                return Response({'code': 403, 'message': '没有系统管理权限'})
                
            # 获取要删除的医生
            try:
                doctor = AdminUser.objects.get(id=doctor_id, is_deleted=False)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '医生不存在或已被删除'})
                
            # 禁止删除自己
            if doctor.id == admin_id:
                return Response({'code': 400, 'message': '不能删除自己的账号'})
                
            # 软删除医生用户
            doctor.is_deleted = True
            doctor.save(update_fields=['is_deleted', 'updated_at'])
            
            logger.info(f"医生用户 {doctor.name}(ID: {doctor.id}) 已被删除")
            
            return Response({
                'code': 200,
                'message': '删除成功'
            })
            
        except Exception as e:
            logger.error(f"删除医生用户失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})

@method_decorator(csrf_exempt, name='dispatch')
class RoleListView(APIView):
    """
    角色列表API视图类
    
    提供获取所有角色列表的功能
    """
    
    def get(self, request):
        """
        获取所有角色列表
        
        返回:
            {'code': 200, 'data': 角色列表}
        """
        try:
            # 检查权限
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 获取所有角色
            roles = Role.objects.all()
            serializer = RoleSerializer(roles, many=True)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
            
        except Exception as e:
            logger.error(f"获取角色列表失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})

@method_decorator(csrf_exempt, name='dispatch')
class ResourceListView(APIView):
    """
    资源列表API视图类
    
    提供获取所有资源列表的功能
    """
    
    def get(self, request):
        """
        获取所有资源列表
        
        参数:
            可选查询参数:
            - pid: 父资源ID，不传则获取所有资源
            
        返回:
            {'code': 200, 'data': 资源列表}
        """
        try:
            # 检查权限
            admin_info = getattr(request, 'admin_info', None)
            if not admin_info:
                return Response({'code': 401, 'message': '未登录'})
                
            # 获取查询参数
            pid = request.query_params.get('pid')
            
            # 构建查询
            query = Resource.objects.all()
            
            # 应用筛选
            if pid:
                if pid == '0':  # 获取顶级资源
                    query = query.filter(pid__isnull=True)
                else:
                    query = query.filter(pid_id=pid)
                    
            # 序列化
            serializer = ResourceSerializer(query, many=True)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
            
        except Exception as e:
            logger.error(f"获取资源列表失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'})

#医生列表
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.core.paginator import Paginator
from apps.background.models import Doctor, Department  # 从正确的应用导入模型
import logging
import json

logger = logging.getLogger(__name__)

class DoctorView(APIView):
    def get(self, request):
        """获取医生列表"""
        try:
            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            
            # 获取所有医生
            doctors = Doctor.objects.all()
            
            # 分页
            paginator = Paginator(doctors, page_size)
            doctors_page = paginator.get_page(page)
            
            # 构建返回数据
            doctor_list = []
            for doctor in doctors_page:
                doctor_list.append({
                    'id': doctor.id,
                    'name': doctor.name,
                    'price': str(doctor.price),
                    'avatar': str(doctor.avatar),
                    'department_id': doctor.department.id,
                    'department_name': doctor.full_department,
                    'title': doctor.title,
                    'tags': doctor.tags,
                    'introduction': doctor.introduction,
                    'campus': doctor.campus
                })
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'total': paginator.count,
                    'results': doctor_list
                }
            })
        except Exception as e:
            logger.error(f"获取医生列表失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

    def post(self, request):
        """添加医生"""
        try:
            data = json.loads(request.body)
            
            # 验证必填字段
            required_fields = ['name', 'department_id', 'title']
            for field in required_fields:
                if not data.get(field):
                    return JsonResponse({'code': 400, 'message': f'缺少必填字段：{field}'})
            
            # 获取科室
            try:
                department = Department.objects.get(id=data['department_id'])
            except Department.DoesNotExist:
                return JsonResponse({'code': 404, 'message': '科室不存在'})
            
            # 创建医生
            doctor = Doctor.objects.create(
                name=data['name'],
                price=data.get('price', 30.00),
                department=department,
                title=data['title'],
                tags=data.get('tags', ''),
                introduction=data.get('introduction', ''),
                campus=data.get('campus', '东院'),
                avatar=data.get('avatar', '/uploads/doctors/d8ba61281d3b7b3df4f93d8bd06d9f6.png')  # 使用固定的默认头像
            )
            
            return JsonResponse({
                'code': 200,
                'message': '添加成功',
                'data': {
                    'id': doctor.id,
                    'name': doctor.name,
                    'price': str(doctor.price),
                    'department_name': doctor.full_department,
                    'title': doctor.title,
                    'tags': doctor.tags,
                    'campus': doctor.campus,
                    'avatar': str(doctor.avatar)
                }
            })
        except Exception as e:
            logger.error(f"添加医生失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

    def post_avatar(self, request, doctor_id):
        """上传医生头像"""
        try:
            try:
                doctor = Doctor.objects.get(id=doctor_id)
            except Doctor.DoesNotExist:
                return JsonResponse({'code': 404, 'message': '医生不存在'})

            if 'avatar' not in request.FILES:
                return JsonResponse({'code': 400, 'message': '未上传头像文件'})

            doctor.avatar = request.FILES['avatar']
            doctor.save()

            return JsonResponse({
                'code': 200,
                'message': '头像上传成功',
                'data': {
                    'avatar_url': str(doctor.avatar)
                }
            })
        except Exception as e:
            logger.error(f"上传医生头像失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

    def put(self, request, doctor_id):
        """修改医生信息"""
        try:
            # 获取医生
            try:
                doctor = Doctor.objects.get(id=doctor_id)
            except Doctor.DoesNotExist:
                return JsonResponse({'code': 404, 'message': '医生不存在'})
            
            data = json.loads(request.body)
            
            # 更新科室
            if 'department_id' in data:
                try:
                    department = Department.objects.get(id=data['department_id'])
                    doctor.department = department
                except Department.DoesNotExist:
                    return JsonResponse({'code': 404, 'message': '科室不存在'})
            
            # 更新其他字段
            fields = ['name', 'price', 'title', 'tags', 'introduction', 'campus']
            for field in fields:
                if field in data:
                    setattr(doctor, field, data[field])
            
            # 如果有新的头像文件
            if 'avatar' in request.FILES:
                doctor.avatar = request.FILES['avatar']
            
            doctor.save()
            
            return JsonResponse({
                'code': 200,
                'message': '修改成功',
                'data': {
                    'id': doctor.id,
                    'name': doctor.name,
                    'price': str(doctor.price),
                    'department_name': doctor.full_department,
                    'title': doctor.title,
                    'tags': doctor.tags,
                    'campus': doctor.campus
                }
            })
        except Exception as e:
            logger.error(f"修改医生信息失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

    def delete(self, request, doctor_id):
        """删除医生"""
        try:
            try:
                doctor = Doctor.objects.get(id=doctor_id)
            except Doctor.DoesNotExist:
                return JsonResponse({'code': 404, 'message': '医生不存在'})
            
            doctor.delete()
            return JsonResponse({
                'code': 200,
                'message': '删除成功'
            })
        except Exception as e:
            logger.error(f"删除医生失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

# 获取所有科室列表的API
class DepartmentListView(APIView):
    def get(self, request):
        """获取科室列表"""
        try:
            departments = Department.objects.all()
            department_list = []
            for dept in departments:
                department_list.append({
                    'id': dept.id,
                    'name': dept.name,
                    'parent_id': dept.parent.id if dept.parent else None,
                    'parent_name': dept.parent.name if dept.parent else None
                })
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': department_list
            })
        except Exception as e:
            logger.error(f"获取科室列表失败: {str(e)}")
            return JsonResponse({'code': 500, 'message': f'服务器错误：{str(e)}'})

@method_decorator(csrf_exempt, name='dispatch')
class WorkflowViewSet(viewsets.ModelViewSet):
    """
    工作流管理视图集
    
    提供工作流的增删改查功能
    """
    serializer_class = WorkflowSerializer
    
    def get_queryset(self):
        """获取工作流查询集"""
        return Workflow.objects.all()
    
    def list(self, request):
        """
        获取工作流列表
        """
        try:
            # 获取所有工作流
            workflows = self.get_queryset()
            serializer = self.get_serializer(workflows, many=True)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
        except Exception as e:
            logger.error(f"获取工作流列表失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def retrieve(self, request, pk=None):
        """
        获取单个工作流详情
        """
        try:
            # 获取工作流
            try:
                workflow = self.get_queryset().get(pk=pk)
            except Workflow.DoesNotExist:
                return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            serializer = self.get_serializer(workflow)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
        except Exception as e:
            logger.error(f"获取工作流详情失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def create(self, request):
        """
        创建工作流
        """
        try:
            # 获取请求数据
            data = request.data
            if not data.get('name'):
                return Response({'code': 400, 'message': '工作流名称不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                
            if not data.get('params'):
                return Response({'code': 400, 'message': '参数字段不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                
            # 验证工作流名称唯一性
            if Workflow.objects.filter(name=data.get('name')).exists():
                return Response({'code': 400, 'message': '工作流名称已存在'}, status=status.HTTP_400_BAD_REQUEST)
                
            # 创建序列化器
            serializer = self.get_serializer(data=data)
            
            # 验证数据
            if not serializer.is_valid():
                return Response({'code': 400, 'message': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
                
            # 创建工作流
            workflow = serializer.save()
            
            logger.info(f"工作流 {workflow.name}(ID: {workflow.id}) 已创建")
            
            return Response({
                'code': 200,
                'message': '创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        except Exception as e:
            logger.error(f"创建工作流失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def update(self, request, pk=None):
        """
        更新工作流
        """
        try:
            # 获取工作流
            try:
                workflow = self.get_queryset().get(pk=pk)
            except Workflow.DoesNotExist:
                return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 验证工作流名称唯一性
            name = request.data.get('name')
            if name and name != workflow.name and Workflow.objects.filter(name=name).exists():
                return Response({'code': 400, 'message': '工作流名称已存在'}, status=status.HTTP_400_BAD_REQUEST)
                
            # 验证数据
            serializer = self.get_serializer(workflow, data=request.data, partial=True)
            if not serializer.is_valid():
                return Response({'code': 400, 'message': serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
                
            # 更新工作流
            workflow = serializer.save()
            
            logger.info(f"工作流 {workflow.name}(ID: {workflow.id}) 已更新")
            
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })
        except Exception as e:
            logger.error(f"更新工作流失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def destroy(self, request, pk=None):
        """
        删除工作流
        """
        try:
            # 获取工作流
            try:
                workflow = self.get_queryset().get(pk=pk)
            except Workflow.DoesNotExist:
                return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 删除工作流
            workflow_name = workflow.name
            workflow_id = workflow.id
            workflow.delete()
            
            logger.info(f"工作流 {workflow_name}(ID: {workflow_id}) 已删除")
            
            return Response({
                'code': 200,
                'message': '删除成功'
            })
        except Exception as e:
            logger.error(f"删除工作流失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    @action(detail=True, methods=['get', 'put'])
    def fields(self, request, pk=None):
        """
        获取或更新工作流字段配置
        
        GET: 获取字段配置
        PUT: 更新字段配置
        """
        try:
            # 获取工作流
            try:
                workflow = self.get_queryset().get(pk=pk)
            except Workflow.DoesNotExist:
                return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 处理GET请求
            if request.method == 'GET':
                # 获取字段配置
                params = workflow.params
                
                # 如果params为空，返回空对象
                if not params:
                    return Response({
                        'code': 200,
                        'message': '获取成功',
                        'data': {}
                    })
                    
                # 返回原始参数字符串，前端负责解析
                return Response({
                    'code': 200,
                    'message': '获取成功',
                    'data': params
                })
            
            # 处理PUT请求
            elif request.method == 'PUT':
                # 获取请求数据
                data = request.data
                
                # 验证数据格式
                if not isinstance(data, dict) and not isinstance(data, str):
                    return Response({'code': 400, 'message': '字段配置格式不正确'}, status=status.HTTP_400_BAD_REQUEST)
                    
                # 如果是字典，转换为符合格式的字符串
                if isinstance(data, dict):
                    # 转换为 {{字段1:值1},{字段2:值2}} 格式
                    fields_str = "{"
                    for field_name, field_value in data.items():
                        fields_str += f"{{{field_name}:{field_value}}},"
                    # 移除最后一个逗号并添加结束括号
                    if fields_str.endswith(","):
                        fields_str = fields_str[:-1]
                    fields_str += "}"
                    params = fields_str
                else:
                    # 已经是字符串，直接使用
                    params = data
                    
                # 更新工作流字段配置
                workflow.params = params
                workflow.save(update_fields=['params', 'updated_at'])
                
                logger.info(f"工作流 {workflow.name}(ID: {workflow.id}) 的字段配置已更新")
                
                return Response({
                    'code': 200,
                    'message': '更新成功',
                    'data': params
                })
                
        except Exception as e:
            logger.error(f"操作工作流字段配置失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'服务器错误：{str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class WorkflowPermissionViewSet(viewsets.ModelViewSet):
    """工作流权限管理视图集"""
    queryset = WorkflowPermission.objects.all()
    serializer_class = WorkflowPermissionSerializer

class PositionViewSet(viewsets.ModelViewSet):
    """职位管理视图集"""
    queryset = Position.objects.all()
    serializer_class = PositionSerializer

class WorkflowApprovalNodeViewSet(viewsets.ModelViewSet):
    """工作流审批节点管理视图集"""
    queryset = WorkflowApprovalNode.objects.all()
    serializer_class = WorkflowApprovalNodeSerializer
    
    def get_queryset(self):
        queryset = WorkflowApprovalNode.objects.all()
        workflow_id = self.request.query_params.get('workflow_id')
        if workflow_id:
            queryset = queryset.filter(workflow_id=workflow_id)
        return queryset.order_by('level')

class TaskViewSet(viewsets.ModelViewSet):
    """任务管理视图集"""
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
    
    def get_queryset(self):
        queryset = Task.objects.all()
        workflow_id = self.request.query_params.get('workflow_id')
        task_status = self.request.query_params.get('task_status')
        user_id = self.request.query_params.get('user_id')
        
        if workflow_id:
            queryset = queryset.filter(workflow_id=workflow_id)
        if task_status:
            queryset = queryset.filter(task_status=task_status)
        if user_id:
            queryset = queryset.filter(Q(userid=user_id) | Q(next_audit=user_id))
            
        return queryset.order_by('-created_at')

class AuditRecordViewSet(viewsets.ModelViewSet):
    """审批记录管理视图集"""
    queryset = AuditRecord.objects.all()
    serializer_class = AuditRecordSerializer
    
    def get_queryset(self):
        queryset = AuditRecord.objects.all()
        task_id = self.request.query_params.get('task_id')
        if task_id:
            queryset = queryset.filter(task_id=task_id)
        return queryset.order_by('-audit_time')

class WorkflowDashboardView(APIView):
    """工作流仪表盘视图"""
    def get(self, request):
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response({"error": "用户ID不能为空"}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 直接获取所有状态为1的工作流，不进行权限过滤
            workflows = Workflow.objects.filter(status=1)
            
            # 序列化工作流数据
            serializer = WorkflowSerializer(workflows, many=True)
            
            return Response(serializer.data)
        except Exception as e:
            logger.error(f"获取工作流仪表盘数据失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({"error": f"获取工作流仪表盘数据失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class WorkflowFormView(APIView):
    """工作流表单视图"""
    def get(self, request, workflow_id):
        try:
            workflow = Workflow.objects.get(id=workflow_id)
            serializer = WorkflowSerializer(workflow)
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
        except Workflow.DoesNotExist:
            return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logger.error(f"获取工作流表单失败: {str(e)}")
            return Response({'code': 500, 'message': f'获取工作流表单失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request, workflow_id):
        try:
            workflow = Workflow.objects.get(id=workflow_id)
            user_id = request.data.get('user_id')
            form_data = request.data.get('form_data')
            task_name = request.data.get('task_name')
            
            if not user_id or not form_data or not task_name:
                return Response({'code': 400, 'message': '用户ID、表单数据和任务名称不能为空'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证表单数据是否符合工作流参数定义
            try:
                form_json = json.dumps(form_data)
                workflow_params = json.loads(workflow.params)
                # 这里可以添加更详细的表单验证逻辑
            except:
                return Response({'code': 400, 'message': '表单数据格式不正确'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 获取用户信息
            user = AdminUser.objects.get(id=user_id)
            
            # 创建任务
            task = Task(
                name=task_name,
                params=form_json,
                workflow_id=workflow,
                userid=user,
                task_status=2  # 设置为审批中状态
            )
            
            # 查找第一个审批节点
            first_node = WorkflowApprovalNode.objects.filter(
                workflow_id=workflow_id, 
                level=1
            ).first()
            
            # 如果没有找到审批节点，返回错误
            if not first_node:
                return Response({'code': 400, 'message': '工作流审批节点配置不正确，请先配置审批节点'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 查找符合条件的审批人
            if first_node.type == 1:  # 部门内部审批
                # 获取职位对象
                position = Position.objects.get(id=first_node.position_id.id)
                # 查找同名的角色
                try:
                    role = Role.objects.get(name=position.name)
                    next_approver = AdminUser.objects.filter(
                            role_id=role.id,
                        department=user.department
                    ).first()
                except Role.DoesNotExist:
                    logger.error(f"未找到与职位 '{position.name}' 对应的角色")
                    return Response({'code': 400, 'message': f"未找到与职位 '{position.name}' 对应的角色"}, status=status.HTTP_400_BAD_REQUEST)
            else:  # 公共审批
                # 获取职位对象
                position = Position.objects.get(id=first_node.position_id.id)
                # 查找同名的角色
                try:
                    role = Role.objects.get(name=position.name)
                    next_approver = AdminUser.objects.filter(
                            role_id=role.id
                    ).first()
                except Role.DoesNotExist:
                    logger.error(f"未找到与职位 '{position.name}' 对应的角色")
                    return Response({'code': 400, 'message': f"未找到与职位 '{position.name}' 对应的角色"}, status=status.HTTP_400_BAD_REQUEST)
            
            # 如果没有找到审批人，返回错误
            if not next_approver:
                return Response({'code': 400, 'message': '未找到合适的审批人，请确保有用户被分配了对应的角色'}, status=status.HTTP_400_BAD_REQUEST)
            
            task.next_audit = next_approver
            task.save()
            
            serializer = TaskSerializer(task)
            return Response({
                'code': 201,
                'message': '提交成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        except Workflow.DoesNotExist:
            return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
        except AdminUser.DoesNotExist:
            return Response({'code': 404, 'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logger.error(f"提交工作流表单失败: {str(e)}")
            return Response({'code': 500, 'message': f'提交工作流表单失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class TaskApprovalView(APIView):
    """任务审批视图"""
    def post(self, request, task_id):
        try:
            task = Task.objects.get(id=task_id)
            user_id = request.data.get('user_id')
            approval_status = request.data.get('approval_status')  # 1通过，2拒绝
            comment = request.data.get('comment', '')
            
            if not user_id or approval_status not in [1, 2]:
                return Response({"error": "用户ID和审批状态不能为空，审批状态必须是1(通过)或2(拒绝)"}, 
                               status=status.HTTP_400_BAD_REQUEST)
            
            # 验证当前用户是否为该任务的审批人
            if task.next_audit_id != int(user_id):
                return Response({"error": "您不是该任务的当前审批人"}, status=status.HTTP_403_FORBIDDEN)
            
            # 验证任务是否处于可审批状态
            if task.task_status not in [1, 2]:  # 新建或审批中
                return Response({"error": "该任务当前状态不可审批"}, status=status.HTTP_400_BAD_REQUEST)
            
            # 获取审批用户
            user = AdminUser.objects.get(id=user_id)
            
            # 创建审批记录
            audit_record = AuditRecord(
                task_id=task,
                audit_user=user,
                audit_status=approval_status,
                comment=comment,
                level=task.current_level
            )
            audit_record.save()
            
            # 处理审批结果
            if approval_status == 2:  # 拒绝
                task.task_status = 4  # 已拒绝
                task.next_audit = None
                task.save()
                return Response({"message": "已拒绝该任务"}, status=status.HTTP_200_OK)
            else:  # 通过
                # 查找下一个审批节点
                next_node = WorkflowApprovalNode.objects.filter(
                    workflow_id=task.workflow_id,
                    level=task.current_level + 1
                ).first()
                
                if not next_node:  # 没有下一个节点，审批完成
                    task.task_status = 3  # 已通过
                    task.next_audit = None
                    task.save()
                    return Response({"message": "任务已全部审批通过"}, status=status.HTTP_200_OK)
                else:  # 有下一个节点，继续审批
                    # 查找符合条件的审批人
                    if next_node.type == 1:  # 部门内部审批
                        # 获取职位对象
                        position = Position.objects.get(id=next_node.position_id.id)
                        # 查找同名的角色
                        try:
                            role = Role.objects.get(name=position.name)
                            next_approver = AdminUser.objects.filter(
                                role_id=role.id,
                                department=task.userid.department
                            ).first()
                        except Role.DoesNotExist:
                            logger.error(f"未找到与职位 '{position.name}' 对应的角色")
                            return Response({"error": f"未找到与职位 '{position.name}' 对应的角色"}, status=status.HTTP_400_BAD_REQUEST)
                    else:  # 公共审批
                        # 获取职位对象
                        position = Position.objects.get(id=next_node.position_id.id)
                        # 查找同名的角色
                        try:
                            role = Role.objects.get(name=position.name)
                            next_approver = AdminUser.objects.filter(
                                role_id=role.id
                            ).first()
                        except Role.DoesNotExist:
                            logger.error(f"未找到与职位 '{position.name}' 对应的角色")
                            return Response({"error": f"未找到与职位 '{position.name}' 对应的角色"}, status=status.HTTP_400_BAD_REQUEST)
                    
                    if not next_approver:
                        return Response({"error": "未找到下一级审批人"}, status=status.HTTP_400_BAD_REQUEST)
                    
                    task.current_level += 1
                    task.next_audit = next_approver
                    task.save()
                    return Response({"message": "已通过当前审批，进入下一级审批"}, status=status.HTTP_200_OK)
                
        except Task.DoesNotExist:
            return Response({"error": "任务不存在"}, status=status.HTTP_404_NOT_FOUND)
        except AdminUser.DoesNotExist:
            return Response({"error": "用户不存在"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            logger.error(f"审批任务失败: {str(e)}")
            return Response({"error": f"审批任务失败: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class MyTasksView(APIView):
    """我的任务视图"""
    def get(self, request):
        user_id = request.query_params.get('user_id')
        task_type = request.query_params.get('task_type', 'pending')  # pending待审批, created我创建的
        
        if not user_id:
            return Response({'code': 400, 'message': '用户ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            if task_type == 'pending':
                # 查询待我审批的任务
                tasks = Task.objects.filter(next_audit=user_id).order_by('-created_at')
            else:
                # 查询我创建的任务
                tasks = Task.objects.filter(userid=user_id).order_by('-created_at')
            
            serializer = TaskSerializer(tasks, many=True)
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': serializer.data
            })
        except Exception as e:
            logger.error(f"获取我的任务失败: {str(e)}")
            return Response({'code': 500, 'message': f'获取我的任务失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class TaskDetailView(APIView):
    """任务详情视图"""
    def get(self, request, task_id):
        """获取任务详情，包括审批记录和表单数据"""
        try:
            # 获取任务
            try:
                task = Task.objects.get(id=task_id)
            except Task.DoesNotExist:
                return Response({'code': 404, 'message': '任务不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 序列化任务数据
            task_serializer = TaskSerializer(task)
            
            # 获取审批记录
            audit_records = AuditRecord.objects.filter(task_id=task).order_by('level')
            audit_serializer = AuditRecordSerializer(audit_records, many=True)
            
            # 获取表单参数数据
            try:
                form_data = json.loads(task.params)
            except:
                form_data = {}
            
            # 获取工作流模板信息
            workflow_serializer = WorkflowSerializer(task.workflow_id)
            
            # 获取下一个审批节点信息（如果有）
            next_node = None
            if task.task_status == 2:  # 审批中
                next_node_obj = WorkflowApprovalNode.objects.filter(
                    workflow_id=task.workflow_id,
                    level=task.current_level
                ).first()
                
                if next_node_obj:
                    next_node = WorkflowApprovalNodeSerializer(next_node_obj).data
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'task': task_serializer.data,
                    'workflow': workflow_serializer.data,
                    'audit_records': audit_serializer.data,
                    'form_data': form_data,
                    'next_node': next_node
                }
            })
        except Exception as e:
            logger.error(f"获取任务详情失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'获取任务详情失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class TaskHistoryView(APIView):
    """任务审批历史视图"""
    def get(self, request, task_id):
        """获取任务审批历史记录"""
        try:
            # 获取任务
            try:
                task = Task.objects.get(id=task_id)
            except Task.DoesNotExist:
                return Response({'code': 404, 'message': '任务不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 获取审批记录
            audit_records = AuditRecord.objects.filter(task_id=task).order_by('audit_time')
            
            # 构建详细的审批历史记录，包含审批人信息
            history_records = []
            for record in audit_records:
                history_records.append({
                    'id': record.id,
                    'level': record.level,
                    'audit_user_id': record.audit_user.id,
                    'audit_user_name': record.audit_user.name,
                    'audit_status': record.audit_status,
                    'audit_status_display': '通过' if record.audit_status == 1 else '拒绝',
                    'comment': record.comment,
                    'audit_time': record.audit_time.strftime('%Y-%m-%d %H:%M:%S')
                })
            
            # 获取工作流节点信息，用于显示完整的审批流程
            workflow_nodes = WorkflowApprovalNode.objects.filter(
                workflow_id=task.workflow_id
            ).order_by('level')
            
            nodes_data = []
            for node in workflow_nodes:
                position = node.position_id
                node_data = {
                    'id': node.id,
                    'level': node.level,
                    'position_id': position.id,
                    'position_name': position.name,
                    'type': node.type,
                    'type_display': '部门内部' if node.type == 1 else '公共'
                }
                
                # 查找该节点的审批记录
                node_record = next((r for r in audit_records if r.level == node.level), None)
                if node_record:
                    node_data['status'] = node_record.audit_status
                    node_data['status_display'] = '通过' if node_record.audit_status == 1 else '拒绝'
                    node_data['audit_user_name'] = node_record.audit_user.name
                    node_data['audit_time'] = node_record.audit_time.strftime('%Y-%m-%d %H:%M:%S')
                    node_data['comment'] = node_record.comment
                else:
                    # 节点未审批
                    if task.current_level == node.level and task.task_status == 2:
                        node_data['status'] = 0  # 审批中
                        node_data['status_display'] = '审批中'
                        if task.next_audit:
                            node_data['audit_user_name'] = task.next_audit.name
                    elif task.current_level > node.level:
                        node_data['status'] = -1  # 已跳过
                        node_data['status_display'] = '已跳过'
                    else:
                        node_data['status'] = -2  # 未到达
                        node_data['status_display'] = '未到达'
                
                nodes_data.append(node_data)
            
            # 获取任务基本信息
            task_info = {
                'id': task.id,
                'name': task.name,
                'workflow_id': task.workflow_id.id,
                'workflow_name': task.workflow_id.name,
                'status': task.task_status,
                'status_display': task.get_task_status_display(),
                'applicant_id': task.userid.id,
                'applicant_name': task.userid.name,
                'current_level': task.current_level,
                'created_at': task.created_at.strftime('%Y-%m-%d %H:%M:%S')
            }
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'task': task_info,
                    'history': history_records,
                    'nodes': nodes_data
                }
            })
        except Exception as e:
            logger.error(f"获取任务审批历史失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'获取任务审批历史失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class TaskFlowView(APIView):
    """任务流程图视图"""
    def get(self, request, task_id):
        """获取任务流程图数据"""
        try:
            # 获取任务
            try:
                task = Task.objects.get(id=task_id)
            except Task.DoesNotExist:
                return Response({'code': 404, 'message': '任务不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 获取审批记录
            audit_records = AuditRecord.objects.filter(task_id=task).order_by('level')
            
            # 获取工作流节点信息
            workflow_nodes = WorkflowApprovalNode.objects.filter(
                workflow_id=task.workflow_id
            ).order_by('level')
            
            # 构建流程图数据
            flow_data = {
                'nodes': [],
                'links': [],
                'task': {
                    'id': task.id,
                    'name': task.name,
                    'status': task.task_status,
                    'status_display': task.get_task_status_display(),
                    'workflow_name': task.workflow_id.name,
                    'applicant_name': task.userid.name,
                    'current_level': task.current_level,
                    'created_at': task.created_at.strftime('%Y-%m-%d %H:%M:%S')
                }
            }
            
            # 添加申请人节点
            flow_data['nodes'].append({
                'id': 'applicant',
                'name': task.userid.name,
                'role': '申请人',
                'status': 1,  # 已完成
                'type': 'applicant'
            })
            
            # 为每个审批节点添加节点和连接
            previous_node_id = 'applicant'
            
            for node in workflow_nodes:
                position = node.position_id
                node_id = f"node_{node.level}"
                
                # 查找该节点的审批记录
                node_record = next((r for r in audit_records if r.level == node.level), None)
                
                # 确定节点状态
                if node_record:
                    # 已审批
                    status = node_record.audit_status
                    status_display = '通过' if node_record.audit_status == 1 else '拒绝'
                    auditor_name = node_record.audit_user.name
                    audit_time = node_record.audit_time.strftime('%Y-%m-%d %H:%M:%S')
                    comment = node_record.comment
                elif task.current_level == node.level and task.task_status == 2:
                    # 审批中
                    status = 0
                    status_display = '审批中'
                    auditor_name = task.next_audit.name if task.next_audit else '未指定'
                    audit_time = None
                    comment = None
                elif task.current_level > node.level:
                    # 已跳过
                    status = -1
                    status_display = '已跳过'
                    auditor_name = None
                    audit_time = None
                    comment = None
                else:
                    # 未到达
                    status = -2
                    status_display = '未到达'
                    auditor_name = None
                    audit_time = None
                    comment = None
                
                # 添加节点
                node_data = {
                    'id': node_id,
                    'name': position.name,
                    'level': node.level,
                    'type': 'approver',
                    'approval_type': '部门内部' if node.type == 1 else '公共',
                    'status': status,
                    'status_display': status_display
                }
                
                if auditor_name:
                    node_data['auditor_name'] = auditor_name
                if audit_time:
                    node_data['audit_time'] = audit_time
                if comment:
                    node_data['comment'] = comment
                
                flow_data['nodes'].append(node_data)
                
                # 添加连接
                flow_data['links'].append({
                    'source': previous_node_id,
                    'target': node_id,
                    'status': status
                })
                
                previous_node_id = node_id
            
            # 添加结束节点
            flow_data['nodes'].append({
                'id': 'end',
                'name': '结束',
                'type': 'end',
                'status': 1 if task.task_status in [3, 4] else -2  # 已完成或未到达
            })
            
            # 添加最后一个连接到结束节点
            flow_data['links'].append({
                'source': previous_node_id,
                'target': 'end',
                'status': 1 if task.task_status in [3, 4] else -2  # 已完成或未到达
            })
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': flow_data
            })
        except Exception as e:
            logger.error(f"获取任务流程图失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'获取任务流程图失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class UserAuditRecordsView(APIView):
    """用户审批记录视图"""
    def get(self, request):
        """获取指定用户处理过的所有审批记录"""
        try:
            # 获取用户ID
            user_id = request.query_params.get('user_id')
            if not user_id:
                return Response({'code': 400, 'message': '用户ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)
            
            # 查询该用户处理过的所有审批记录
            try:
                user = AdminUser.objects.get(id=user_id)
            except AdminUser.DoesNotExist:
                return Response({'code': 404, 'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            # 查询该用户的所有审批记录
            audit_records = AuditRecord.objects.filter(audit_user=user).order_by('-audit_time')
            
            # 获取分页参数
            page = int(request.query_params.get('page', 1))
            page_size = int(request.query_params.get('page_size', 10))
            
            # 应用分页
            start = (page - 1) * page_size
            end = start + page_size
            paginated_records = audit_records[start:end]
            
            # 构建审批记录详情，包含任务和工作流信息
            result = []
            for record in paginated_records:
                task = record.task_id
                workflow = task.workflow_id
                
                record_data = {
                    'id': record.id,
                    'task_id': task.id,
                    'task_name': task.name,
                    'workflow_id': workflow.id,
                    'workflow_name': workflow.name,
                    'applicant_id': task.userid.id,
                    'applicant_name': task.userid.name,
                    'audit_status': record.audit_status,
                    'audit_status_display': '通过' if record.audit_status == 1 else '拒绝',
                    'comment': record.comment,
                    'level': record.level,
                    'audit_time': record.audit_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'task_status': task.task_status,
                    'task_status_display': task.get_task_status_display()
                }
                
                # 获取表单数据
                try:
                    form_data = json.loads(task.params)
                    record_data['form_data'] = form_data
                except:
                    record_data['form_data'] = {}
                
                result.append(record_data)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'total': audit_records.count(),
                    'page': page,
                    'page_size': page_size,
                    'records': result
                }
            })
        except Exception as e:
            logger.error(f"获取用户审批记录失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'获取用户审批记录失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class WorkflowNodeConfigView(APIView):
    """工作流审批节点配置视图"""
    def get(self, request, workflow_id):
        """获取工作流的审批节点配置"""
        try:
            # 检查工作流是否存在
            try:
                workflow = Workflow.objects.get(id=workflow_id)
            except Workflow.DoesNotExist:
                return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 获取工作流的审批节点
            nodes = WorkflowApprovalNode.objects.filter(workflow_id=workflow_id).order_by('level')
            
            # 序列化节点数据
            serializer = WorkflowApprovalNodeSerializer(nodes, many=True)
            
            # 获取所有职位，供前端选择
            positions = Position.objects.all()
            position_serializer = PositionSerializer(positions, many=True)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'nodes': serializer.data,
                    'positions': position_serializer.data
                }
            })
        except Exception as e:
            logger.error(f"获取工作流审批节点配置失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'获取工作流审批节点配置失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def post(self, request, workflow_id):
        """添加工作流审批节点"""
        try:
            # 检查工作流是否存在
            try:
                workflow = Workflow.objects.get(id=workflow_id)
            except Workflow.DoesNotExist:
                return Response({'code': 404, 'message': '工作流不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 获取请求数据
            data = request.data
            position_id = data.get('position_id')
            level = data.get('level')
            approval_type = data.get('type', 1)  # 默认为部门内部审批
            
            # 验证数据
            if not position_id:
                return Response({'code': 400, 'message': '职位ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                
            if not level:
                return Response({'code': 400, 'message': '审批级别不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                
            # 检查职位是否存在
            try:
                position = Position.objects.get(id=position_id)
            except Position.DoesNotExist:
                return Response({'code': 404, 'message': '职位不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 检查是否已存在相同级别的审批节点
            if WorkflowApprovalNode.objects.filter(workflow_id=workflow_id, level=level).exists():
                return Response({'code': 400, 'message': f'已存在级别为 {level} 的审批节点'}, status=status.HTTP_400_BAD_REQUEST)
                
            # 创建审批节点
            node = WorkflowApprovalNode.objects.create(
                workflow_id=workflow,
                position_id=position,
                level=level,
                type=approval_type
            )
            
            # 序列化返回数据
            serializer = WorkflowApprovalNodeSerializer(node)
            
            return Response({
                'code': 201,
                'message': '添加成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        except Exception as e:
            logger.error(f"添加工作流审批节点失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'添加工作流审批节点失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def put(self, request, workflow_id, node_id):
        """更新工作流审批节点"""
        try:
            # 检查节点是否存在
            try:
                node = WorkflowApprovalNode.objects.get(id=node_id, workflow_id=workflow_id)
            except WorkflowApprovalNode.DoesNotExist:
                return Response({'code': 404, 'message': '审批节点不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 获取请求数据
            data = request.data
            position_id = data.get('position_id')
            level = data.get('level')
            approval_type = data.get('type')
            
            # 更新数据
            if position_id:
                try:
                    position = Position.objects.get(id=position_id)
                    node.position_id = position
                except Position.DoesNotExist:
                    return Response({'code': 404, 'message': '职位不存在'}, status=status.HTTP_404_NOT_FOUND)
            
            if level:
                # 检查是否已存在相同级别的其他审批节点
                if WorkflowApprovalNode.objects.filter(workflow_id=workflow_id, level=level).exclude(id=node_id).exists():
                    return Response({'code': 400, 'message': f'已存在级别为 {level} 的审批节点'}, status=status.HTTP_400_BAD_REQUEST)
                node.level = level
                
            if approval_type is not None:
                node.type = approval_type
                
            node.save()
            
            # 序列化返回数据
            serializer = WorkflowApprovalNodeSerializer(node)
            
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })
        except Exception as e:
            logger.error(f"更新工作流审批节点失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'更新工作流审批节点失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request, workflow_id, node_id):
        """删除工作流审批节点"""
        try:
            # 检查节点是否存在
            try:
                node = WorkflowApprovalNode.objects.get(id=node_id, workflow_id=workflow_id)
            except WorkflowApprovalNode.DoesNotExist:
                return Response({'code': 404, 'message': '审批节点不存在'}, status=status.HTTP_404_NOT_FOUND)
                
            # 删除节点
            node.delete()
            
            return Response({
                'code': 200,
                'message': '删除成功'
            })
        except Exception as e:
            logger.error(f"删除工作流审批节点失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'删除工作流审批节点失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class SystemSetupView(APIView):
    """系统设置视图，用于快速配置工作流所需的基础数据"""
    
    def post(self, request):
        """快速添加职位并关联角色和用户"""
        try:
            data = request.data
            action = data.get('action')
            
            if action == 'add_position':
                # 添加职位
                name = data.get('name')
                if not name:
                    return Response({'code': 400, 'message': '职位名称不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                    
                # 检查是否已存在
                if Position.objects.filter(name=name).exists():
                    position = Position.objects.get(name=name)
                    return Response({
                        'code': 200, 
                        'message': '职位已存在', 
                        'data': PositionSerializer(position).data
                    })
                    
                # 创建职位
                position = Position.objects.create(name=name)
                
                # 同时创建同名角色（如果不存在）
                if not Role.objects.filter(name=name).exists():
                    role = Role.objects.create(name=name)
                    logger.info(f"创建了与职位 '{name}' 同名的角色")
                else:
                    role = Role.objects.get(name=name)
                    logger.info(f"职位 '{name}' 对应的角色已存在")
                
                return Response({
                    'code': 201, 
                    'message': '职位添加成功', 
                    'data': {
                        'position': PositionSerializer(position).data,
                        'role': RoleSerializer(role).data
                    }
                })
                
            elif action == 'assign_role':
                # 将角色分配给用户
                user_id = data.get('user_id')
                role_id = data.get('role_id')
                
                if not user_id or not role_id:
                    return Response({'code': 400, 'message': '用户ID和角色ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                
                # 查找用户和角色
                try:
                    user = AdminUser.objects.get(id=user_id)
                except AdminUser.DoesNotExist:
                    return Response({'code': 404, 'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
                    
                try:
                    role = Role.objects.get(id=role_id)
                except Role.DoesNotExist:
                    return Response({'code': 404, 'message': '角色不存在'}, status=status.HTTP_404_NOT_FOUND)
                
                # 分配角色
                user.role = role
                user.save(update_fields=['role', 'updated_at'])
                
                return Response({
                    'code': 200, 
                    'message': '角色分配成功', 
                    'data': {
                        'user': AdminUserSerializer(user).data,
                        'role': RoleSerializer(role).data
                    }
                })
                
            elif action == 'list_users_by_role':
                # 列出拥有特定角色的用户
                role_id = data.get('role_id')
                
                if not role_id:
                    return Response({'code': 400, 'message': '角色ID不能为空'}, status=status.HTTP_400_BAD_REQUEST)
                    
                try:
                    role = Role.objects.get(id=role_id)
                except Role.DoesNotExist:
                    return Response({'code': 404, 'message': '角色不存在'}, status=status.HTTP_404_NOT_FOUND)
                    
                users = AdminUser.objects.filter(role=role, is_deleted=False)
                
                return Response({
                    'code': 200, 
                    'message': '获取成功', 
                    'data': {
                        'role': RoleSerializer(role).data,
                        'users': AdminUserSerializer(users, many=True).data
                    }
                })
                
            else:
                return Response({'code': 400, 'message': '不支持的操作类型'}, status=status.HTTP_400_BAD_REQUEST)
                
        except Exception as e:
            logger.error(f"系统设置操作失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'系统设置操作失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def get(self, request):
        """获取系统基础数据"""
        try:
            # 获取所有职位
            positions = Position.objects.all()
            
            # 获取所有角色
            roles = Role.objects.all()
            
            # 获取所有管理员用户
            users = AdminUser.objects.filter(is_deleted=False)
            
            return Response({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'positions': PositionSerializer(positions, many=True).data,
                    'roles': RoleSerializer(roles, many=True).data,
                    'users': AdminUserSerializer(users, many=True).data
                }
            })
        except Exception as e:
            logger.error(f"获取系统基础数据失败: {str(e)}")
            import traceback
            logger.error(traceback.format_exc())
            return Response({'code': 500, 'message': f'获取系统基础数据失败: {str(e)}'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

